import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Row, Col, Table, Button, message, Modal, Space } from 'antd'
import { VideoCameraOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import style from './Index.module.less'
import { formatDate } from '@js/tool'
const { confirm } = Modal
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: '单位',
      dataIndex: 'structure',
      key: 'structure'
    },
    {
      title: '报名时间',
      dataIndex: 'participation_datetime',
      key: 'participation_datetime',
      render: (v) => formatDate(v, 'YYYY-MM-DD HH:mm')
    },
    {
      title: '签到',
      dataIndex: 'participation_datetime',
      key: 'participation_datetime',
      render: (v) => {
        return v ? '是' : '否'
      }
    }
  ]
}
class VideoMeetingDetail extends Component {
  state = {
    list: [],
    loading: false,
    visible: false,
    modifyData: {},
    liveData: {},
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  // 获取直播数据
  getLiveData () {
    return this.$get(`/api/xapc/live/${this.props.meta.id}`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          liveData: res.data
        })
      })
  }

  // 获取基础数据
  getBaseData () {
    const hide = message.loading('加载中', 120)
    Promise.all([this.getLiveData()])
      .then(res => {
        hide()
      })
      .catch(() => hide())
  }

  // 获取参会人员列表
  getPerson () {
    const { current, pageSize } = this.state.pagination
    this.setState({ loading: true })
    this.$get('/api/xapc/live/participantlist', {
      liveid: this.props.meta.id,
      current,
      page_size: pageSize
    }).then(res => {
      this.setState({ loading: false })
      this.setState({
        list: res.data.list.map((li, i) => {
          li.order = i + 1
          return li
        }),
        pagination: {
          ...this.state.pagination,
          total: res.data.total
        }
      })
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getPerson()
    })
  }

  // 二次确认
  confirm (content, callback = () => {}) {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content,
      onOk () {
        callback()
      },
      okText: '确定',
      cancelText: '取消'
    })
  }

  // 开始会议
  startHandle () {
    this.updateMeeting({
      status: '会议开始',
      live_begin_datetime: Math.floor(Date.now() / 1000)
    })
  }

  // 结束会议
  endHandle () {
    this.updateMeeting({
      status: '会议结束',
      live_end_datetime: Math.floor(Date.now() / 1000)
    })
  }

  // 完成会议
  signUpHandle () {
    this.updateMeeting({
      status: '报名'
    })
  }

  updateMeeting (data = {}, callback = () => {}) {
    const hide = message.loading('加载中', 120)
    this.$put(`/api/xapc/live/${this.props.meta.id}`, data).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.getBaseData()
      callback()
    }).catch(() => hide())
  }

  // 显示上传笔录
  showUpload () {
    this.setState({
      uploadVisible: true
    })
  }

  toVideo (d) {
    if (!d.chair_joinuri) {
      return message.warning('视频庭审地址不存在')
    }
    window.open(d.chair_joinuri, '_blank')
  }

  componentDidMount () {
    this.getBaseData()
    this.getPerson()
  }

  renderBtns () {
    if (!this.state.liveData || !this.state.liveData.id) {
      return null
    }
    const d = this.state.liveData
    const s = d.status
    if (s === '草稿') {
      return (
        <>
          <Button type='primary' onClick={() => this.confirm('您确定要开启报名吗？', () => this.signUpHandle())}>开启报名</Button>
        </>
      )
    }
    if (s === '报名') {
      return (
        <>
          <Button type='primary' onClick={() => this.confirm('您确定要开始会议吗？', () => this.startHandle())}>会议开始</Button>
        </>
      )
    }
    if (['会议开始'].indexOf(s) !== -1) {
      return (
        <>
          <Button type='primary' onClick={() => this.confirm('您确定要结束会议吗？', () => this.endHandle())}>结束会议</Button>
          <Button type='primary' ghost onClick={() => window.open(d.chair_joinuri)}>前往直播(主持人密码：{d.chairpwd})</Button>
        </>
      )
    }
  }

  render () {
    const data = this.state.liveData || {}
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style.header}>
          <div className={style.title}>
            <div className={style['title-icon']}>
              <VideoCameraOutlined />
            </div>
            <div className={style['title-text']}>
              <span>{data.title}</span>
            </div>
          </div>
        </div>
        <div className={style['basic-info']}>
          <Row>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>会议类型：</div>
                <div className={style['basic-cell-text']}>{data.isonline === 1 ? '线上直播' : '线下开会'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>开始时间：</div>
                <div className={style['basic-cell-text']}>{formatDate(data.begin_datetime, 'YYYY-MM-DD HH:mm')}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>结束时间：</div>
                <div className={style['basic-cell-text']}>{formatDate(data.end_datetime, 'YYYY-MM-DD HH:mm')}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>报名人数：</div>
                <div className={style['basic-cell-text']}>{data.participant_no || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>报名截止：</div>
                <div className={style['basic-cell-text']}>{formatDate(data.registration_deadline, 'YYYY-MM-DD HH:mm')}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>创建人：</div>
                <div className={style['basic-cell-text']}>{data.operator || '无'}</div>
              </div>
            </Col>
            <Col span={8}>
              <div className={style['basic-cell']}>
                <div className={style['basic-cell-label']}>状态：</div>
                <div className={style['basic-cell-text']}>{data.status}</div>
              </div>
            </Col>
            {
              data.status === '会议开始' && (
                <>
                  <Col span={8}>
                    <div className={style['basic-cell']}>
                      <div className={style['basic-cell-label']}>会议id：</div>
                      <div className={style['basic-cell-text']}>{data.conferenceid}</div>
                    </div>
                  </Col>
                  <Col span={8}>
                    <div className={style['basic-cell']}>
                      <div className={style['basic-cell-label']}>嘉宾密码：</div>
                      <div className={style['basic-cell-text']}>{data.generalpwd}</div>
                    </div>
                  </Col>
                  <Col span={8}>
                    <div className={style['basic-cell']}>
                      <div className={style['basic-cell-label']}>观众密码：</div>
                      <div className={style['basic-cell-text']}>{data.audiencepwd}</div>
                    </div>
                  </Col>
                </>
              )
            }
          </Row>
        </div>

        <div className={style['btn-line']}>
          <Space>
            {this.renderBtns()}
          </Space>
        </div>

        <div className={style['table-container']}>
          <Table loading={this.state.loading} rowKey='order' columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}
const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(VideoMeetingDetail)
